package com.hedl.practice.diyJava.network_programming.j_email.utils;

import javax.activation.DataHandler;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class SendEmail {

    final String smtpHost;
    final String username;
    final String password;
    final boolean debug;

    public SendEmail(String smtpHost, String username, String password) {
        this.smtpHost = smtpHost;
        this.username = username;
        this.password = password;
        this.debug = true;
    }

    public Session createSSLSession(){
        Properties props = new Properties();
        props.put("mail.smtp.host",this.smtpHost);  //SMTP主机名
        props.put("mail.smtp.port","465");  //主机端口
        props.put("mail.smtp.auth","true"); //是否需要用户认证

        //启动SSL:
        props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.port","465");
        Session session = Session.getInstance(props, new Authenticator() {
            //用户名+口令认证
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(SendEmail.this.username,SendEmail.this.password);
            }
        });
        session.setDebug(this.debug);   //显示调试信息
        return session;
    }

    public Session createTLSSession(){
        Properties props = new Properties();
        props.put("mail.smtp.host", this.smtpHost); // SMTP主机名
        props.put("mail.smtp.port", "587"); // 主机端口号
        props.put("mail.smtp.auth", "true"); // 是否需要用户认证
        props.put("mail.smtp.starttls.enable", "true"); // 启用TLS加密
        Session session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(SendEmail.this.username, SendEmail.this.password);
            }
        });
        session.setDebug(this.debug); // 显示调试信息
        return session;
    }

    public Session createInsecureSession(String host,String username,String password){
        Properties props = new Properties();
        props.put("mail.smtp.host", this.smtpHost); // SMTP主机名
        props.put("mail.smtp.port", "25"); // 主机端口号
        props.put("mail.smtp.auth", "true"); // 是否需要用户认证
        Session session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(SendEmail.this.username, SendEmail.this.password);
            }
        });
        session.setDebug(this.debug); // 显示调试信息
        return session;
    }

    public Message createTestMessage(Session session,String from,String to,String subject,String body) throws MessagingException {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
        message.setSubject(subject,"UTF-8");
        message.setText(body,"UTF-8");
        return message;
    }

    public Message createTestMessageHtml(Session session,String from,String to,String subject,String body) throws MessagingException {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
        message.setSubject(subject,"UTF-8");
        message.setText(body,"UTF-8","html");
        return message;
    }

    //发送附件调用此方法
    public Message createMessageWithAttachment(Session session, String from, String to, String subject, String body, String fileName, InputStream input) throws MessagingException, IOException {
        //创建默认的 MimeMessage 对象
        MimeMessage message = new MimeMessage(session);     //邮件服务器
        message.setFrom(new InternetAddress(from));     //发送者邮件号
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));        //目的地邮箱
        message.setSubject(subject, "UTF-8");       //邮件头

        Multipart multipart = new MimeMultipart();
        // 添加text:
        BodyPart textpart = new MimeBodyPart();     //创建一个MimeBodyPart对象，用于存放附件
        textpart.setContent(body, "text/plain;charset=utf-8");      //正文内容
        multipart.addBodyPart(textpart);        //将附件添加到multipart对象中
        // 添加image:
        BodyPart imagepart = new MimeBodyPart();        //用于存放邮件正文
        imagepart.setFileName(fileName);        //附件名称
        //设置附件内容时，使用的是"application/octet-stream"类型。这是一种通用的二进制流类型，适用于任何类型的文件
        imagepart.setDataHandler(new DataHandler(new ByteArrayDataSource(input, "application/octet-stream")));
        multipart.addBodyPart(imagepart);
        message.setContent(multipart);
        return message;
    }

    public Message createMessageWithInlineImage(Session session, String from, String to, String subject, String body, String fileName, InputStream input) throws MessagingException, IOException {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject, "UTF-8");

        Multipart multipart = new MimeMultipart();
        // 添加text:
        BodyPart textpart = new MimeBodyPart();
        textpart.setContent(body, "text/html;charset=utf-8");
        multipart.addBodyPart(textpart);
        // 添加image:
        BodyPart imagepart = new MimeBodyPart();
        imagepart.setFileName(fileName);
        imagepart.setDataHandler(new DataHandler(new ByteArrayDataSource(input, "image/jpeg")));
        // 与HTML的<img src="cid:img01">关联:
        imagepart.setHeader("Content-ID", "<img01>");
        multipart.addBodyPart(imagepart);
        message.setContent(multipart);      //设置内容
        return message;
    }

}
